package org.eddm.widget;

import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.io.IOException;

import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.bridge.DocumentLoader;
import org.apache.batik.bridge.GVTBuilder;
import org.apache.batik.bridge.UserAgent;
import org.apache.batik.bridge.UserAgentAdapter;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.gvt.GraphicsNode;
import org.apache.batik.util.XMLResourceDescriptor;
import org.netbeans.api.visual.widget.Scene;
import org.netbeans.api.visual.widget.Widget;
import org.w3c.dom.svg.SVGDocument;

public class SVGWidget extends Widget{

	private GraphicsNode rootGN;
	private static int boundGap = 10;
	private String nodeID;
	
	public String getNodeID() {
		return nodeID;
	}

	public void setNodeID(String nodeID) {
		this.nodeID = nodeID;
	}

	public SVGWidget(Scene scene, String uri, String nodeID) throws IOException {
		super(scene);
		setSvgUri(uri);
		this.nodeID = nodeID;
	}
	
	public SVGWidget(Scene scene) {
		super(scene);
	}
	
	public void setSvgUri(String uri) throws IOException {
		String parser = XMLResourceDescriptor.getXMLParserClassName();
		SAXSVGDocumentFactory df = new SAXSVGDocumentFactory(parser);
		SVGDocument doc = df.createSVGDocument(uri);
		UserAgent userAgent = new UserAgentAdapter();
		DocumentLoader loader = new DocumentLoader(userAgent);
		BridgeContext ctx = new BridgeContext(userAgent, loader);
		ctx.setDynamicState(BridgeContext.DYNAMIC);
		GVTBuilder builder = new GVTBuilder();
		rootGN = builder.build(ctx, doc);
		revalidate();
    }
	
	protected Rectangle calculateClientArea() {
		Rectangle2D rect2D = rootGN.getBounds();
		if(rect2D != null) {
			Rectangle rec = rootGN.getBounds().getBounds();
			rec.setRect(rec.getX()-boundGap, rec.getY()-boundGap, rec.getWidth()+boundGap, rec.getHeight()+boundGap);
			return rec;
		}
		
		return null;		
	}
	
	protected void paintWidget() {
		if (null != rootGN) {
			Graphics2D g = getGraphics();
			
			Rectangle2D svgSize = rootGN.getBounds();
			Rectangle2D widgetSize = this.getBounds();
			double sx = ((widgetSize.getWidth()-(2*boundGap))  /svgSize.getWidth());//-0.045;
			double sy = ((widgetSize.getHeight()-(2*boundGap)) /svgSize.getHeight());//-0.043;

			AffineTransform afTranslate = AffineTransform.getTranslateInstance(widgetSize.getX()+boundGap, widgetSize.getY()+boundGap);
			AffineTransform afScale = AffineTransform.getScaleInstance(sx , sy );
						
			afTranslate.concatenate(afScale);
			
			rootGN.setTransform(afTranslate);
			rootGN.paint(g);
		}
	}
}